package com.ucampus.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.ucampus.service.userLoginService;
/**
 * 功能：
 * 作者： 启明星_Polaris
 * 日期：2025/1/7 下午8:41
 **/

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private userLoginService userLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求头中的 Token
        String token = request.getHeader("Authorization");

        // 获取请求中的用户 ID（假设是通过 URL 参数传递）
        String userIdFromRequest = request.getParameter("id");

        if (token == null || token.isEmpty() || userIdFromRequest == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置为 401
            response.getWriter().write("Unauthorized: No Token Provided or User ID Missing");
            return false;
        }

        // 去掉 "Bearer " 前缀
        String jwtToken = token.replace("Bearer ", "");

        // 输出调试信息，查看传入的 Token 和用户 ID
        System.out.println("Received Token: " + jwtToken);
        System.out.println("User ID from Request: " + userIdFromRequest);

        // 验证 token 的有效性
        boolean isValidToken = userLoginService.validateToken(jwtToken, userIdFromRequest);

        // 输出验证结果
        System.out.println("Token validation result: " + isValidToken);

        if (!isValidToken) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized: Invalid Token");
            return false;
        }
        return true;
    }
}
